import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import {
  Input,
  message,
  Button,
  Avatar,
  Card,
  Modal,
  Alert,
  Tag,
  Icon,
  List,
  Spin,
  AutoComplete,
  Select,
  Divider,
  Tooltip,
} from 'antd'
import { Trans, withI18n } from '@lingui/react'
import { UserLink } from 'components'
import { connect } from 'dva'

// const FormItem = Form.Item
const Search = Input.Search
const { Meta } = Card
const { Option } = AutoComplete

@withI18n()
@connect(({ devices }) => {
  const { geoinputsuggestions } = devices
  return { geoinputsuggestions }
})
class InputSuggestion extends PureComponent {
  state = {
    search: '',
  }
  render() {
    const { geoinputsuggestions, oncenterandzoom, i18n, dispatch } = this.props
    const { search } = this.state
    const auto = true
    return (
      <div>
        {auto ? (
          <AutoComplete
            placeholder={i18n.t`Please select project coordinates`}
            // dataSource={geoinputsuggestions}
            style={{ width: '100%' }}
            // onSelect={onSelect}
            onSelect={value => {
              if (oncenterandzoom) oncenterandzoom(JSON.parse(value))
              // console.log('search：' + value)
            }}
            // onSearch={value => {
            //   console.log('on search：' + value)
            // }}
            // value={search}
            onChange={e => {
              dispatch({
                type: 'devices/InputGeosuggestion',
                payload: e,
              }).then(result => {
                dispatch({
                  type: 'devices/updateState',
                  payload: {
                    geoinputsuggestions:
                      result && result.result ? result.result : [],
                  },
                })
              })
            }}
          >
            {geoinputsuggestions.map(item => {
              return (
                <Option
                  key={JSON.stringify({
                    uid: item.uid,
                    location: item.location,
                    city: item.city,
                  })}
                  // children={
                  //   <div style={{ display: 'flex', justifyContent: 'space-between' }}
                  //     onClick={e => {
                  //       this.setState({
                  //         search: item.name
                  //       })
                  //     }}>
                  //     <span style={{ color: 'rgba(48,48,48,1)', fontSize: 15, fontWeight: 'bold' }}>{item.name}</span>
                  //     <span style={{ color: 'rgba(128,128,128,1)', fontSize: 14 }}>{item.city}</span>
                  //   </div>
                  // }
                >
                  {item.name} {item.city}
                </Option>
              )
            })}
          </AutoComplete>
        ) : (
          <Input onChange={e => {}} />
        )}
      </div>
    )
  }
}

@withI18n()
@connect(({ devices, loading }) => {
  const { createProjectVisible, editingproject, projects } = devices
  return { createProjectVisible, loading, editingproject, projects }
})
class WorkerModal extends PureComponent {
  map = undefined
  markpoint = undefined
  inputref = undefined
  inputref2 = undefined
  inputref3 = undefined
  state = {
    locationloading: false,
    selectedLocation: undefined,
    chooseCity: undefined,
    searchstr: '',
    searchsuccess: false,
    ProjectName: '',
  }
  handleOk = () => {
    const {
      onOk,
      editingproject,
      dispatch,
      i18n,
      onCancel,
      createProjectVisible,
    } = this.props
    const { selectedLocation, chooseCity, searchstr, ProjectName } = this.state
    if (!ProjectName) {
      message.info(i18n.t`Please input Project Name`)
      return
    }
    if (!selectedLocation) {
      message.info(
        i18n.t`Please enter the project address and select coordinates in the map`
      )
      return
    }
    if (editingproject) {
      dispatch({
        type: 'devices/projectrename',
        payload: {
          projectid: editingproject,
          ProjectName,
          Geo: `${selectedLocation.lat},${selectedLocation.lng}`,
        },
      }).then(() => {
        dispatch({
          type: 'devices/projects',
        })
      })
    } else {
      dispatch({
        type: 'devices/newproject',
        payload: {
          ProjectName,
          Geo: `${selectedLocation.lat},${selectedLocation.lng}`,
          Address: searchstr,
          City: chooseCity,
        },
      }).then(() => {
        dispatch({
          type: 'devices/projects',
        })
      })
    }
  }
  relocation = () => {
    const { dispatch } = this.props
    const setstate = newstate => {
      this.setState(newstate)
    }
    setstate({ locationloading: true })

    const initMap = this.initMap
    var geolocation = new BMap.Geolocation()
    geolocation.enableSDKLocation()
    geolocation.getCurrentPosition(function(r) {
      if (this.getStatus() == BMAP_STATUS_SUCCESS) {
        var map = initMap()
        map.centerAndZoom(r.point, 15)
        // var mk = new BMap.Marker(r.point);
        // map.addOverlay(mk);
        map.panTo(r.point)
        // var lng = r.point.lng, lat = r.point.lat

        // console.log('region:' + r.point.lng + ',' + r.point.lat)
        // dispatch({
        //   type: 'devices/convertPoint',
        //   payload: { lng: r.point.lng, lat: r.point.lat }
        // }).then(data => {

        //   const { result } = data
        //   if (result && result.length > 0) {
        //     let geo1 = result[0]
        //     console.log(JSON.stringify(geo1))

        //     let point = new BMap.Point(geo1['x'], geo1['y'])
        //     var map = new BMap.Map("allmap");
        //     map.centerAndZoom(point, 20);

        //     var mk = new BMap.Marker(point);
        //     map.addOverlay(mk);
        //     map.panTo(point);
        //   }
        // })
        // alert('您的位置：' + r.point.lng + ',' + r.point.lat);
      } else {
        // alert('failed');
      }
      setstate({ locationloading: false })
    })
  }
  decodeAddress(address) {
    const modal = window.projectcreatemodal
    const { chooseCity } = modal.state
    console.log(chooseCity)
    var myGeo = new BMap.Geocoder()
    // 将地址解析结果显示在地图上，并调整地图视野
    myGeo.getPoint(
      address,
      function(point) {
        if (point) {
          modal.centerAndZoom(point)
          modal.setState({ searchsuccess: true })
        } else {
          modal.setState({ searchsuccess: false })
        }
      },
      chooseCity
    )
  }
  centerAndZoom = value => {
    const modal = window.projectcreatemodal

    var map = this.initMap()
    map.centerAndZoom(new BMap.Point(value.lng, value.lat), 17)
    modal.choosePoint(value, map)
  }

  choosePoint(location, map = undefined) {
    const modal = window.projectcreatemodal
    if (!map) map = modal.initMap()
    var tmppoint = new BMap.Point(location.lng, location.lat)
    map.removeOverlay(modal.markpoint)
    modal.markpoint = new BMap.Marker(tmppoint)
    map.addOverlay(modal.markpoint)
    map.panTo(tmppoint)
    modal.setState({ selectedLocation: location, locationloading: false })
  }
  initMap() {
    const modal = window.projectcreatemodal

    var map = undefined
    const initcontrols = () => {
      var opts = { anchor: BMAP_ANCHOR_BOTTOM_RIGHT }
      map.enableScrollWheelZoom(true)
      map.addControl(new BMap.MapTypeControl())
      map.addControl(new BMap.ScaleControl(opts))
      map.addControl(new BMap.NavigationControl())
      var xArr = 0 //存放横坐标
      var yArr = 0 //存放纵坐标
      var endx = 0
      var endy = 0
      var moved = false
      map.addEventListener('touchstart', function(e) {
        //手指触摸屏幕的时候清空两个数组
        // message.info('blur')
        if (modal.inputref) modal.inputref.blur()
        if (modal.inputref2) modal.inputref2.blur()
        if (modal.inputref3) modal.inputref3.blur()
        moved = false
        xArr = e.targetTouches[0].pageX
        yArr = e.targetTouches[0].pageY
        endx = e.targetTouches[0].pageX
        endy = e.targetTouches[0].pageY
      })

      map.addEventListener('touchmove', function(e) {
        //如果滑动了屏幕，xArr和yArr将各存入两个坐标值，即始末坐标值
        // xArr.push(e.targetTouches[0].pageX);
        // yArr.push(e.targetTouches[0].pageY);
        // message.info("touchmove")
        moved = true
        endx = e.targetTouches[0].pageX
        endy = e.targetTouches[0].pageY
      })

      map.addEventListener('touchend', function(e) {
        // var endx = e.targetTouches[0].pageX
        // var endy = e.targetTouches[0].pageY
        var far
        var flag = true
        //计算平移距离，区分滑动事件和点击事件
        // if ((xArr> 1) && (yArr.length > 1)) {
        far = Math.abs(xArr - endx) ^ (2 + Math.abs(yArr - endy)) ^ 2
        if (far > 0) {
          flag = false
        }
        // }
        if (flag) {
          modal.choosePoint(e.point, map)
        }
      })
      map.addEventListener('click', function(e) {
        modal.choosePoint(e.point, map)
      })
      // map.setCurrentCity("北京");
      var geolocationControl = new BMap.GeolocationControl(opts)
      geolocationControl.addEventListener('click', function(e) {
        console.log(e)
      })
      geolocationControl.addEventListener('locationSuccess', function(e) {
        // 定位成功事件
        // var address = '';
        // address += e.addressComponent.province;
        // address += e.addressComponent.city;
        // address += e.addressComponent.district;
        // address += e.addressComponent.street;
        // address += e.addressComponent.streetNumber;
        // alert("当前定位地址为：" + address);
        // console.log(e.target.xD)
        modal.centerAndZoom(e.target.xD)
      })
      geolocationControl.addEventListener('locationError', function(e) {
        alert(e.message)
      })
      map.addControl(geolocationControl)
      console.log('add geolocation')
    }
    if (modal.map) {
      map = modal.map
    } else {
      map = new BMap.Map('allmap')
      initcontrols()
    }
    modal.map = map
    return map
  }
  componentDidMount() {
    window.projectcreatemodal = this

    const { editingproject, projects } = this.props
    let targetprojectdata = undefined
    if (editingproject) {
      targetprojectdata = projects.find(_ => _.objectId == editingproject)
    }
    // console.log("targetprojectdata:" + JSON.stringify(targetprojectdata))
    if (targetprojectdata) {
      let geo = targetprojectdata.Geo.split(',')
      this.setState({
        ProjectName: targetprojectdata.ProjectName,
        chooseCity: targetprojectdata.City,
        searchstr: targetprojectdata.Address,
        searchsuccess: true,
        // selectedLocation: { lat: parseFloat(geo[0]), lng: parseFloat(geo[1]) }
      })
      setTimeout(() => {
        this.centerAndZoom({ lat: parseFloat(geo[0]), lng: parseFloat(geo[1]) })
      }, 10)
    } else {
      this.relocation()
    }
  }

  render() {
    const {
      editingproject,
      createProjectVisible,
      projects,
      i18n,
      dispatch,
      loading,
    } = this.props
    const {
      locationloading,
      selectedLocation,
      chooseCity,
      searchstr,
      searchsuccess,
      ProjectName,
    } = this.state
    // let targetprojectdata = undefined
    // if (editingproject) {
    //   targetprojectdata = projects.find(_ => _.objectId == editingproject);
    // }
    const otherprops = {
      maskClosable: true,
      title: editingproject ? i18n.t`Edit Project` : i18n.t`Create Project`,
      centered: true,
      onCancel() {
        dispatch({
          type: 'devices/hideModal',
        })
      },
    }
    const confirmLoading = editingproject
      ? loading.effects[`devices/projectrename`]
      : loading.effects[`devices/newproject`]
    const pharstyle = {
      fontSize: 14,
      color: 'rgba(148,148,148,1)',
      fontWeight: 'bold',
    }
    return (
      <Modal
        {...otherprops}
        visible={createProjectVisible}
        closable={false}
        keyboard={false}
        confirmLoading={confirmLoading}
        okText={i18n.t`Confirm`}
        onOk={this.handleOk}
        style={{
          paddingTop: 0,
        }}
        bodyStyle={{
          paddingTop: 0,
        }}
      >
        <div id={'projectcreatemodal_mapcontainer'}>
          <div style={{ display: 'flex', alignItems: 'center', marginTop: 10 }}>
            <span style={{ width: 145, ...pharstyle }}>
              <Trans>Project Name</Trans>:
            </span>
            <div style={{ width: '100%' }}>
              {/* addonBefore={<Trans>Project Name</Trans>} */}
              <Input
                placeholder={i18n.t`Please input Project Name`}
                value={ProjectName}
                ref={inputref2 => (this.inputref2 = inputref2)}
                onChange={e => {
                  this.setState({ ProjectName: e.target.value })
                }}
              />
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', marginTop: 10 }}>
            {/* <span style={{ width: 100, ...pharstyle }}><Trans>Project Location</Trans>:</span> */}
            <div style={{ width: '100%' }}>
              {/* <InputSuggestion oncenterandzoom={this.centerAndZoom} /> */}
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ width: 145, ...pharstyle }}>
                  {<Trans>Selected latitude and longitude</Trans>}:
                </div>
                <div style={{ width: '100%' }}>
                  {selectedLocation ? (
                    <Tag>
                      <Icon type="environment" />
                      &nbsp;{`${selectedLocation.lat},${selectedLocation.lng}`}
                    </Tag>
                  ) : (
                    <Tag>
                      <Icon type="environment" />
                      &nbsp;<Trans>None</Trans>
                    </Tag>
                  )}
                </div>
              </div>
            </div>
          </div>
          {/* <Tooltip
            title={i18n.t`Click on the map to select longitude and latitude`}
            placement="topRight"
          > */}
          <div
            style={
              selectedLocation
                ? {
                    borderStyle: 'dashed',
                    borderWidth: 1,
                    borderColor: 'rgba(148,148,148,1)',
                    borderRadius: 10,
                    padding: 5,
                    marginTop: 10,
                  }
                : {
                    borderStyle: 'dashed',
                    borderWidth: 1,
                    borderColor: 'red',
                    borderRadius: 10,
                    padding: 5,
                    marginTop: 10,
                  }
            }
          >
            <span
              style={{
                width: '100%',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                color: 'rgb(125,125,125)',
              }}
            >
              <Icon type="info-circle" />
              &nbsp;{i18n.t`Click on the map to select longitude and latitude`}
            </span>

            {/* , justifyContent: 'space-between' */}
            <Input
              disabled={chooseCity == undefined}
              value={searchstr}
              ref={inputref => (this.inputref = inputref)}
              addonBefore={
                <Select
                  showSearch
                  ref={inputref3 => (this.inputref3 = inputref3)}
                  getPopupContainer={() =>
                    document.getElementById('projectcreatemodal_mapcontainer')
                  }
                  placeholder={i18n.t`Select Region`}
                  value={chooseCity}
                  onSelect={value => {
                    // console.log('select')
                    this.setState({ chooseCity: value }, () => {
                      this.decodeAddress(searchstr)
                    })
                  }}
                  style={{ minWidth: 100 }}
                >
                  {provinces.map(item => (
                    <Option value={item.name}>{item.name}</Option>
                  ))}
                </Select>
              }
              placeholder={
                !chooseCity
                  ? i18n.t`Please choose the area first`
                  : i18n.t`Please enter the project address and select coordinates in the map`
              }
              onChange={e => {
                this.setState({ searchstr: e.target.value })
                this.decodeAddress(e.target.value)
              }}
            />
            {/* {!searchsuccess && <span>暂无结果</span>} */}
            <Spin spinning={locationloading}>
              <div
                id="allmap"
                style={
                  // searchsuccess ?
                  {
                    width: '100%',
                    height: 300,
                  }
                  // :{ width: '100%', height: 300, borderStyle: 'dashed', borderColor: 'red', borderWidth: 1 }
                }
              />
            </Spin>
          </div>
          {/* </Tooltip> */}
        </div>
      </Modal>
    )
  }
}
var provinces = [
  {
    name: '北京市',
    center: '116.405285,39.904989',
    type: 0,
    subDistricts: [],
  },
  {
    name: '天津市',
    center: '117.190182,39.125596',
    type: 1,
    subDistricts: [],
  },
  {
    name: '河北省',
    center: '114.502461,38.045474',
    type: 1,
    subDistricts: [],
  },
  {
    name: '山西省',
    center: '112.549248,37.857014',
    type: 1,
    subDistricts: [],
  },
  {
    name: '内蒙古自治区',
    center: '111.670801,40.818311',
    type: 1,
    subDistricts: [],
  },
  {
    name: '辽宁省',
    center: '123.429096,41.796767',
    type: 1,
    subDistricts: [],
  },
  {
    name: '吉林省',
    center: '125.3245,43.886841',
    type: 1,
    subDistricts: [],
  },
  {
    name: '黑龙江省',
    center: '126.642464,45.756967',
    type: 1,
    subDistricts: [],
  },
  {
    name: '上海市',
    center: '121.472644,31.231706',
    type: 1,
    subDistricts: [],
  },
  {
    name: '江苏省',
    center: '118.767413,32.041544',
    type: 1,
    subDistricts: [],
  },
  {
    name: '浙江省',
    center: '120.153576,30.287459',
    type: 1,
    subDistricts: [],
  },
  {
    name: '安徽省',
    center: '117.283042,31.86119',
    type: 1,
    subDistricts: [],
  },
  {
    name: '福建省',
    center: '119.306239,26.075302',
    type: 1,
    subDistricts: [],
  },
  {
    name: '江西省',
    center: '115.892151,28.676493',
    type: 1,
    subDistricts: [],
  },
  {
    name: '山东省',
    center: '117.000923,36.675807',
    type: 1,
    subDistricts: [],
  },
  {
    name: '河南省',
    center: '113.665412,34.757975',
    type: 1,
    subDistricts: [],
  },
  {
    name: '湖北省',
    center: '114.298572,30.584355',
    type: 1,
    subDistricts: [],
  },
  {
    name: '湖南省',
    center: '112.982279,28.19409',
    type: 1,
    subDistricts: [],
  },
  {
    name: '广东省',
    center: '113.280637,23.125178',
    type: 1,
    subDistricts: [],
  },
  {
    name: '广西壮族自治区',
    center: '108.320004,22.82402',
    type: 1,
    subDistricts: [],
  },
  {
    name: '海南省',
    center: '110.33119,20.031971',
    type: 1,
    subDistricts: [],
  },
  {
    name: '重庆市',
    center: '106.504962,29.533155',
    type: 1,
    subDistricts: [],
  },
  {
    name: '四川省',
    center: '104.065735,30.659462',
    type: 1,
    subDistricts: [],
  },
  {
    name: '贵州省',
    center: '106.713478,26.578343',
    type: 1,
    subDistricts: [],
  },
  {
    name: '云南省',
    center: '102.712251,25.040609',
    type: 1,
    subDistricts: [],
  },
  {
    name: '西藏自治区',
    center: '91.132212,29.660361',
    type: 1,
    subDistricts: [],
  },
  {
    name: '陕西省',
    center: '108.948024,34.263161',
    type: 1,
    subDistricts: [],
  },
  {
    name: '甘肃省',
    center: '103.823557,36.058039',
    type: 1,
    subDistricts: [],
  },
  {
    name: '青海省',
    center: '101.778916,36.623178',
    type: 1,
    subDistricts: [],
  },
  {
    name: '宁夏回族自治区',
    center: '106.278179,38.46637',
    type: 1,
    subDistricts: [],
  },
  {
    name: '新疆维吾尔自治区',
    center: '87.617733,43.792818',
    type: 1,
    subDistricts: [],
  },
  {
    name: '台湾省',
    center: '121.509062,25.044332',
    type: 2,
    subDistricts: [],
  },
  {
    name: '香港特別行政區',
    center: '114.173355,22.320048',
    type: 1,
    subDistricts: [],
  },
  {
    name: '澳門特別行政區',
    center: '113.54909,22.198951',
    type: 1,
    subDistricts: [],
  },
]

WorkerModal.propTypes = {
  type: PropTypes.string,
  item: PropTypes.object,
  onOk: PropTypes.func,
}

export default WorkerModal
